package bing

import (
	"log"
	"net/http"
	"reflect"
	"strings"

	"git.oschina.net/alwaysking/hellopage-server/Config"
)

var ConfigCell Config.ConfigStruct
var LogFile *log.Logger

type BackgroundController struct {
}

func InitConfig(config Config.ConfigStruct, log *log.Logger) {
	ConfigCell = config
	LogFile = log
}

func (this *BackgroundController) GetBingDailyAction(w http.ResponseWriter, r *http.Request) {
	jsonpCallbackFunc := r.FormValue("jsoncallback")
	LogFile.Println("接收到 bing每日壁纸请求")

	rv, err := Background_GetURL()
	if err != nil {
		w.Write([]byte("nil"))
		LogFile.Println("bing每日壁纸请求 失败")
		LogFile.Println(err)
		return
	}

	jsonpCallback := jsonpCallbackFunc + "(" + rv + ")"
	w.Write([]byte(jsonpCallback))
}

func Background(w http.ResponseWriter, r *http.Request) {
	pathInfo := strings.Trim(r.URL.Path, "/")
	parts := strings.Split(pathInfo, "/")

	var action = ""
	if len(parts) > 1 {
		action = strings.Title(parts[1]) + "Action"
	}

	// 取得 WeatherController 接口的所有函数的反射值
	login := &BackgroundController{}
	controller := reflect.ValueOf(login)
	// 取出我们需要的方法
	method := controller.MethodByName(action)
	// 处理异常
	if !method.IsValid() {
		method = controller.MethodByName(strings.Title("GetBingDaily") + "Action")
	}

	// 包装参数
	requestValue := reflect.ValueOf(r)
	responseValue := reflect.ValueOf(w)

	// 调用函数
	method.Call([]reflect.Value{responseValue, requestValue})
}
